/*
[Evgeny Myasishchev (24.06.2007)]: Function is used to drop all tables from public schema.
Steps:
1) Drop all constraints for all tables
2) Drop all tables from publick schema
*/
CREATE FUNCTION dropAllTables() RETURNS void AS $func$
DECLARE	
	dropKeys text;
	keyName VARCHAR(1000);
	tableName VARCHAR(1000);
	tableRow RECORD;	
BEGIN
	dropKeys := '';
	--1) Drop all constraints for all tables
	FOR tableRow IN SELECT c.conname, cl.relname FROM pg_constraint c JOIN pg_class cl ON (cl.oid=c.conrelid) WHERE c.contype='f' LOOP
		dropKeys := dropKeys ||
		' ' ||
		'ALTER TABLE ' || tableRow.relname || ' DROP CONSTRAINT ' || tableRow.conname ||
		'; ';

	END LOOP;	
	EXECUTE dropKeys;

	--2) Drop all tables from publick schema
	dropKeys := '';
	FOR tableRow IN SELECT tbl.tablename FROM pg_tables tbl WHERE tbl.schemaname='public' LOOP
		dropKeys := dropKeys ||
		' ' ||
		'DROP TABLE ' || tableRow.tablename ||
		';';
	END LOOP;	
	EXECUTE dropKeys;	
END;
$func$ LANGUAGE plpgsql;

SELECT dropAllTables();

--We don't nead it anymore
DROP FUNCTION dropAllTables();